using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using Appetite.Domain.Models;
using Appetite.Domain.Repository;

namespace Appetite.Data.EntityFramework.Repository
{
    /// <summary>
    /// At this moment, managing Categories is out of scope. We will hardcode a list of categories.
    /// </summary>
    public class RecipeCategoryRepository : IRecipeCategoryRepository
    {
        readonly AppetiteDomainContext context = new AppetiteDomainContext();

        public IQueryable<RecipeCategory> All
        {
            get { return context.RecipeCategories; }
        }

        public IQueryable<RecipeCategory> AllIncluding(params Expression<Func<RecipeCategory, object>>[] includeProperties)
        {
            IQueryable<RecipeCategory> query = context.RecipeCategories;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public RecipeCategory Find(System.Guid id)
        {
            return context.RecipeCategories.Find(id);
        }

        public void InsertOrUpdate(RecipeCategory recipecategory)
        {
            if (recipecategory.Id == default(System.Guid))
            {
                // New entity
                recipecategory.Id = GuidHelper.NewSequentialGuid();
                context.RecipeCategories.Add(recipecategory);
            }
            else
            {
                // Existing entity
                recipecategory.ModificationDate = DateTime.Now;
                context.Entry(recipecategory).State = EntityState.Modified;
            }
        }

        public void Delete(System.Guid id)
        {
            var recipecategory = context.RecipeCategories.Find(id);
            context.RecipeCategories.Remove(recipecategory);
        }

        public void Save()
        {
            context.SaveChanges();
        }
    }
}
